﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AIS.SDK.Api.Response;
using AIS.SDK.Common;
using AIS.SDK.Handler;
using AIS.SDK.Model;
using AISservice.Common;
using AISservice.Entity;
using Common;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;

namespace AISservice.Controllers
{
    /// <summary>
    /// 促销价格设置
    /// </summary>
    [Route("api/v1/[controller]/[action]")]
    [ApiController]
    public class P4072Controller : ControllerBase
    {
        /// <summary>
        /// 新增一条促销价格
        /// </summary>
        /// <param name="objpram"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult<MQResponse> CreatePromotePrice(dynamic objpram)
        {
            Log4Net.Debug(objpram);
            Console.WriteLine(objpram);
            //string username = objpram["username"].ToString();
            //string password = objpram["password"].ToString();
            //string orderid = objpram["orderid"].ToString();
            //用了新的方式，哈哈方便多了
            P4072param param = Common.JsonHelper.JsonToObject<P4072param>(((Newtonsoft.Json.Linq.JObject)objpram).ToString());
            MQResponse execresult = new MQResponse() { ResponseCode = "200" };
            int stackId = 0;
            int stateId = 0;
            string rid = "";

            try
            {
                if (string.IsNullOrWhiteSpace(param.username) || string.IsNullOrWhiteSpace(param.password))
                {
                    throw new MQException("401", "请求的用户名或密码为空！");
                }
                string token = SomeHandler.GetToken(param.username, param.password);

                if (string.IsNullOrWhiteSpace(token))
                {
                    throw new MQException("401", "验证失败，请检查用户名密码是否正确！");
                }


                Console.WriteLine("上传促销价格,准备新增一条");

                FormRequest formRequest = new FormRequest()
                {
                    returnControlIDs = "1[14,72,38,7,43,37,34,24,11]",
                    formName = "P4072_W4072B",
                    version = "MBR001A",
                    formServiceAction = "R",
                    bypassFormServiceEREvent = true
                      ,
                    formActions = new FormActionsCollection
                                    (
                                        new FSREvent[]
                                        {
                                              new FSREvent() { controlID="86", command="SetControlValue" ,value="ZPROMOTE" },
                                              new FSREvent() { controlID="1[38]", command="SetQBEValue"  ,value=param.itemgroup },
                                              new FSREvent() { controlID="1[72]", command="SetQBEValue"  ,value=param.itemnumber },//me码
                                              new FSREvent() { controlID="1[7]",  command="SetQBEValue"  ,value=param.clientnumber },//地址号
                                              new FSREvent() { controlID="1[43]", command="SetQBEValue"  ,value=param.clientgroup },//客户组
                                              new FSREvent() { controlID="6", command="DoAction"  }
                                        }
                                    )
                };
                ApplicationStackRequest asrequest = new ApplicationStackRequest()
                {
                    action = "open",
                    outputType = "VERSION2",
                    formName = "P4072_W4072B",
                    stackId = stackId,
                    stateId = stateId,
                    formRequest = formRequest
                };

                AppstackResponse response = AISClientHandler.Instance.Appstack_execute(token, asrequest);
                //Console.WriteLine(response.JsonString);
                stackId = response.stackId;
                stateId = response.stateId;
                rid = response.rid;

                if (CommonHandler.ValidateReturnValue(response.JsonString, "fs_P4072_W4072B"))
                {
                    Console.WriteLine("点击新增按钮");
                    ActionRequest actionRequest = new ActionRequest()
                    {
                        formOID = "W4072B",
                        formActions = new FormActionsCollection
                              (
                                  new FSREvent[]
                                  {
                                    new FSREvent() { controlID="67", command="DoAction"  }
                                  }
                              )
                    };

                    asrequest = new ApplicationStackRequest()
                    {
                        outputType = "VERSION2",
                        allowCache = true,
                        action = "execute",
                        actionRequest = actionRequest,
                        stackId = stackId,
                        stateId = stateId,
                        rid = response.rid
                    };
                    response = AISClientHandler.Instance.Appstack_execute(token, asrequest);
                    stackId = response.stackId;
                    stateId = response.stateId;
                    rid = response.rid;
                    if (CommonHandler.ValidateReturnValue(response.JsonString, "fs_P40073_W40073F"))
                    {
                        Console.WriteLine("选择不同的类型");
                        string pricetype = param.settype;
                        //根据类型，找到具体的行数
                        JObject obj = response.ToJObject();
                        int rowcount = Convert.ToInt32(obj["fs_P40073_W40073F"]["data"]["gridData"]["summary"]["records"]);
                        int rowindex = -1;
                        for (int i = 0; i < rowcount; i++)
                        {
                            if (obj["fs_P40073_W40073F"]["data"]["gridData"]["rowset"][i]["z_DL01_8"]["value"].ToString().Equals(pricetype))
                            {
                                rowindex = Convert.ToInt32(obj["fs_P40073_W40073F"]["data"]["gridData"]["rowset"][i]["rowIndex"]);
                            }
                        }
                        if (rowindex < 0)
                        {
                            throw new MQException("404","找不到对应的价格类型！");
                        }
                        actionRequest = new ActionRequest()
                        {
                            formOID = "W40073F",
                            formActions = new FormActionsCollection
                                  (
                                      new FSREvent[]
                                      {
                                          new FSREvent() { controlID=$"1.{rowindex.ToString()}", command="SelectRow"   },
                                          new FSREvent() { controlID="4", command="DoAction"  }
                                      }
                                  )
                        };

                        asrequest = new ApplicationStackRequest()
                        {
                            outputType = "VERSION2",
                            allowCache = true,
                            action = "execute",
                            actionRequest = actionRequest,
                            stackId = stackId,
                            stateId = stateId,
                            rid = response.rid
                        };
                        response = AISClientHandler.Instance.Appstack_execute(token, asrequest);
                        stackId = response.stackId;
                        stateId = response.stateId;
                        rid = response.rid;
                        if (CommonHandler.ValidateReturnValue(response.JsonString, "fs_P4072_W4072A"))
                        {
                            Console.WriteLine("填写价格信息");
                            List<gridrowInsertevents> gridrows = new List<gridrowInsertevents>();
                            FormActionsCollection fs = new FormActionsCollection();

                            gridcolumnCollection col = new gridcolumnCollection();

                            col.Add(new gridcolumnevent() { columnID = "218", value = param.quantityfrom.ToString(), command = "SetGridCellValue" });
                            col.Add(new gridcolumnevent() { columnID = "7", value = param.unit, command = "SetGridCellValue" });
                            col.Add(new gridcolumnevent() { columnID = "14", value = param.factorvalue.ToString(), command = "SetGridCellValue" });
                            col.Add(new gridcolumnevent() { columnID = "11", value = param.basiscode, command = "SetGridCellValue" });
                            col.Add(new gridcolumnevent() { columnID = "6", value =param.currencycode , command = "SetGridCellValue" });
                            col.Add(new gridcolumnevent() { columnID = "10", value = param.DateEffective.ToString("yyyy/MM/dd", System.Globalization.DateTimeFormatInfo.InvariantInfo), command = "SetGridCellValue" });
                            col.Add(new gridcolumnevent() { columnID = "9", value = param.DateExpired.ToString("yyyy/MM/dd", System.Globalization.DateTimeFormatInfo.InvariantInfo), command = "SetGridCellValue" });

                            col.Add(new gridcolumnevent() { columnID = "173", value = param.clientnumber, command = "SetGridCellValue" });

                            gridrows.Add(new gridrowInsertevents() { gridColumnEvents = col });

                            fs.AddRange(
                                        new FormActionsCollection
                                                 (
                                                     new FSREvent[]
                                                     {
                                                            new FSREvent() { controlID="55", command="SetControlValue", value=param.itemgroup},
                                                            new FSREvent() { controlID="53",command="SetControlValue", value=param.clientgroup },
                                                            new FSREvent() { controlID="59", command="SetControlValue", value=param.itemnumber}
                                                     }
                                                 )
                                       );
                            GridAction gridAction = new GridAction();
                            gridAction.gridID = "1";
                            gridAction.gridRowInsertEvents = gridrows;

                            fs.Add(new FSREvent() { command = "SelectRow", gridAction = gridAction });
                            fs.Add(new FSREvent() { command = "DoAction", controlID = "4" });


                            actionRequest = new ActionRequest()
                            {
                                //returnControlIDs = "1[348,440,257,45,46,47,48,49,50,51]",
                                formOID = "W4072A",
                                formActions =  fs
                            };
                            asrequest = new ApplicationStackRequest()
                            {
                                outputType = "VERSION2",
                                allowCache = true,
                                action = "execute",
                                actionRequest = actionRequest,
                                stackId = response.stackId,//上一次返回的值
                                stateId = response.stateId,
                                rid = response.rid
                            };

                            response = AISClientHandler.Instance.Appstack_execute(token, asrequest);
                            if (response.currentApp.Contains("P4072_W4072A"))
                            {
                                //修改不成功，验证是否有异常信息
                                CommonHandler.ValidateReturnValue(response.JsonString, "fs_P4072_W4072A");
                            }
                            else
                            {
                                execresult.Result = "999";
                                execresult.Message = response.JsonString;
                            }
                        }


                    }
                }


            }
            catch (MQException x)
            {
                Log4Net.Error($"请求异常:{x.Message}");
                Console.WriteLine($"请求异常:{x.Message}");
                execresult.ResponseCode = CommonHandler.GetException(x.Message, "CODE", x.ExceptionCode).ToString();
                execresult.Message = CommonHandler.GetException(x.Message, "DESC", x.Message).ToString().Replace("\u000a", Environment.NewLine);
            }
            return execresult;

        }

        [HttpPost]
        public ActionResult<MQResponse>  ModifyPromotePrice(dynamic objpram)
        {
            Log4Net.Debug(objpram);
            Console.WriteLine(objpram);
            //string username = objpram["username"].ToString();
            //string password = objpram["password"].ToString();
            //string orderid = objpram["orderid"].ToString();
            //用了新的方式，哈哈方便多了
            P4072param param = Common.JsonHelper.JsonToObject<P4072param>(((Newtonsoft.Json.Linq.JObject)objpram).ToString());
            MQResponse execresult = new MQResponse() { ResponseCode = "200" };
            int stackId = 0;
            int stateId = 0;
            string rid = "";

            try
            {
                if (string.IsNullOrWhiteSpace(param.username) || string.IsNullOrWhiteSpace(param.password))
                {
                    throw new MQException("401", "请求的用户名或密码为空！");
                }
                OAuthController oAuth = new OAuthController();
                oAuth.GetToken(objpram);
                if (string.IsNullOrWhiteSpace(SomeHandler.GetToken(param.username)))
                {
                    throw new MQException("401", "验证失败，请检查用户名密码是否正确！");
                }
                string token = SomeHandler.GetToken(param.username);

                Console.WriteLine("上传促销价格,准备修改已存在的");

                FormRequest formRequest = new FormRequest()
                {
                    returnControlIDs = "1[14,72,38,7,43,37,34,24,11]",
                    formName = "P4072_W4072B",
                    version = "MBR001A",
                    formServiceAction = "R",
                    bypassFormServiceEREvent = true
                       ,
                    formActions = new FormActionsCollection
                                     (
                                         new FSREvent[]
                                         {
                                              new FSREvent() { controlID="86", command="SetControlValue" ,value="ZPROMOTE" },
                                              new FSREvent() { controlID="1[38]", command="SetQBEValue" ,value=param.itemgroup},
                                              new FSREvent() { controlID="1[72]", command="SetQBEValue" ,value=param.itemnumber },//me码
                                              new FSREvent() { controlID="1[7]", command="SetQBEValue" ,value=param.clientnumber },//地址号
                                              new FSREvent() { controlID="1[43]", command="SetQBEValue" ,value=param.clientgroup },//客户组
                                              new FSREvent() { controlID="6", command="DoAction"  }
                                         }
                                     )
                };
                ApplicationStackRequest asrequest = new ApplicationStackRequest()
                {
                    action = "open",
                    outputType = "VERSION2",
                    formName = "P4072_W4072B",
                    stackId = stackId,
                    stateId = stateId,
                    formRequest = formRequest
                };

                AppstackResponse response = AISClientHandler.Instance.Appstack_execute(token, asrequest);
                //Console.WriteLine(response.JsonString);
                stackId = response.stackId;
                stateId = response.stateId;
                rid = response.rid;
                if (CommonHandler.ValidateReturnValue(response.JsonString, "fs_P4072_W4072B"))
                {
                    JObject obj = response.ToJObject();
                    int rowcount = Convert.ToInt16(obj["fs_P4072_W4072B"]["data"]["gridData"]["summary"]["records"]);
                    Console.WriteLine($"查询到{rowcount}条记录");
                    if (rowcount > 0)
                    {
                        Console.WriteLine("选择第一条记录，并打开编辑界面");
                        ActionRequest actionRequest = new ActionRequest()
                        {
                            returnControlIDs = "1[10,9]",
                            formOID = "W4072B",
                            formActions = new FormActionsCollection
                                  (
                                      new FSREvent[]
                                      {
                                          new FSREvent() { controlID="1.0", command="SelectRow"   },
                                          new FSREvent() { controlID="4", command="DoAction"  }
                                      }
                                  )
                        };

                        asrequest = new ApplicationStackRequest()
                        {
                            outputType = "VERSION2",
                            allowCache = true,
                            action = "execute",
                            actionRequest = actionRequest,
                            stackId = stackId,
                            stateId = stateId,
                            rid = response.rid
                        };
                        response = AISClientHandler.Instance.Appstack_execute(token, asrequest);
                        stackId = response.stackId;
                        stateId = response.stateId;
                        rid = response.rid;
                        if (CommonHandler.ValidateReturnValue(response.JsonString, "fs_P4072_W4072A"))
                        {
                            Console.WriteLine("修改结束时间");
                            obj = response.ToJObject();
                            rowcount = Convert.ToInt32(obj["fs_P4072_W4072A"]["data"]["gridData"]["summary"]["records"]);
                            List<gridrowupdateevents> gridrows = new List<gridrowupdateevents>();
                            List<gridcolumnevent> gridcols = new List<gridcolumnevent>();

                            gridcols.Add(new gridcolumnevent()
                            {
                                columnID = "9",
                                command = "SetGridCellValue",
                                value =param.DateEffective.AddDays(-1).ToString("yyyy/MM/dd", System.Globalization.DateTimeFormatInfo.InvariantInfo)
                            });


                            for (int i = 0; i < rowcount; i++)
                            {
                                stackId = response.stackId;
                                stateId = response.stateId;
                                int rowindex = Convert.ToInt32(obj["fs_P4072_W4072A"]["data"]["gridData"]["rowset"][i]["rowIndex"]);
                                DateTime existDateExpired = Convert.ToDateTime(obj["fs_P4072_W4072A"]["data"]["gridData"]["rowset"][i]["z_EXDJ_9"]["value"]);
                                //判断下日期，如果存在的记录失效日期大于当前生效日期，则需要修改
                                if (DateTime.Compare(existDateExpired, param.DateEffective)>0)
                                {
                                    gridrows.Add(new gridrowupdateevents()
                                    {
                                        gridColumnEvents = gridcols,
                                        rowNumber = rowindex
                                    });
                                }
                            }

                            actionRequest = new ActionRequest()
                            {
                                //returnControlIDs = "1[348,440,257,45,46,47,48,49,50,51]",
                                formOID = "W4072A",
                                formActions = new FormActionsCollection
                                     (
                                         new FSREvent[]
                                         {
                                              new FSREvent() { controlID="1.0", command="SelectRow" ,gridAction =new GridAction(){
                                                  gridID="1",gridRowUpdateEvents=gridrows
                                              } },
                                            new FSREvent() { controlID="4", command="DoAction"  }
                                         }
                                     )
                            };
                            asrequest = new ApplicationStackRequest()
                            {
                                outputType = "VERSION2",
                                allowCache = true,
                                action = "execute",
                                actionRequest = actionRequest,
                                stackId = response.stackId,//上一次返回的值
                                stateId = response.stateId,
                                rid = response.rid
                            };

                            response = AISClientHandler.Instance.Appstack_execute(token, asrequest);
                            stackId = response.stackId;
                            stateId = response.stateId;
                            rid = response.rid;
                             
                            if (response.currentApp.Contains("P4072_W4072A"))
                            {
                                //修改不成功，验证是否有异常信息
                                CommonHandler.ValidateReturnValue(response.JsonString, "fs_P4072_W4072A");
                            }
                            else
                            {
                                if (CommonHandler.ValidateReturnValue(response.JsonString, "fs_P4072_W4072B"))
                                {
                                    Console.WriteLine("修改原纪录成功，开始新增");

                                    actionRequest = new ActionRequest()
                                    {
                                        //returnControlIDs = "1[17,18,19,20]",
                                        formOID = "W4072B"
                                    };
                                    asrequest = new ApplicationStackRequest()
                                    {
                                        outputType = "VERSION2",
                                        allowCache = true,
                                        action = "close",
                                        actionRequest = actionRequest,
                                        stackId = stackId,//上一次返回的值
                                        stateId = stateId,
                                        rid = rid
                                    };
                                    if (!string.IsNullOrWhiteSpace(token))
                                    {
                                        response = AISClientHandler.Instance.Appstack_execute(token, asrequest);
                                        //Console.WriteLine(response.JsonString);
                                    }
                                    Console.Write("close P4072");

                                }
                            }
                        }
                    }
                }
            }
            catch (MQException x)
            {
                Log4Net.Error($"请求异常:{x.Message}");
                Console.WriteLine($"请求异常:{x.Message}");
                execresult.ResponseCode = CommonHandler.GetException(x.Message, "CODE", x.ExceptionCode).ToString();
                execresult.Message = CommonHandler.GetException(x.Message, "DESC", x.Message).ToString().Replace("\u000a", Environment.NewLine);

            }
            return execresult;
        }

    }
}